package com.heima.schedule.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加延迟任务
     *
     * @param task
     * @return
     */
    @Override
    public Long addTask(Task task) {
        //添加任务到数据库中 taskinfo/taskinfologs
        boolean flag = addTaskToDb(task);
        if (flag) {
            //添加任务到redis中
            addTaskToRedis(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        //删除任务，更新日志
        Task task = updateDb(taskId, ScheduleConstants.EXECUTED);
        //删除redis的数据
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }
        return false;
    }

    /**
     * 按照类型和优先级拉取任务
     *
     * @return
     */
    @Override
    public Task pollTask(Integer type, Integer priority) {
        String key = type + "_" + priority;
        String listKey = "list_" + key;

        //从redis中去除数据并删除 -- 空指针
        String taskStr = cacheService.lLeftPop(listKey);
        //类型转化
        Task task = JSON.parseObject(taskStr, Task.class);
        //修改数据库任务，删除任务和修改日志状态
        if (task != null){
            taskinfoMapper.deleteById(task.getTaskId());

            TaskinfoLogs tas = new TaskinfoLogs();
            BeanUtils.copyProperties(task, tas);
            tas.setStatus(1);
            taskinfoLogsMapper.updateById(tas);
        }
        return task;
    }

    /**
     * 定时刷新同步到list中
     */
    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void freshTaskToList() {
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("未来数据定时刷新---定时任务");

            //获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {//future_100_50

                //获取当前数据的key  topic
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];

                //按照key和分值查询符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                //同步数据
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    log.info("成功的将" + futureKey + "刷新到了" + topicKey);
                }
            }
        }
    }

    /**
     * 同步数据库中的redis中的zset中的数据
     */
    @Override
    @Scheduled(cron = "0 */1 * * * ?")
    public void reloadData() {
        //清理redis中的所有数据，list和zset
        Set<String> listKeys = cacheService.scan("list_*");
        Set<String> zsetKeys = cacheService.scan("zset_*");

        cacheService.delete(listKeys);
        cacheService.delete(zsetKeys);
        //查询小于当前时间+5分钟的数据
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                .lt(Taskinfo::getExecuteTime, calendar.getTime()));

        //存入到redis中的zset中
        if(taskinfos != null && taskinfos.size() > 0){
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToRedis(task);
            }
        }
    }

    /**
     * 删除redis中的任务数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {

        String key = task.getTaskType() + "_" + task.getPriority();

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志状态
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("task cancel exception taskid={}", taskId);
        }

        return task;

    }

    /**
     * 添加任务到redis中
     *
     * @param task
     */
    private void addTaskToRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        String listKey = "list_" + key;
        String zsetKey = "zset_" + key;

        //获取未来五分钟
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //存储到list中
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(listKey, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= calendar.getTimeInMillis()) {
            cacheService.zAdd(zsetKey, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库中 taskinfo/taskinfologs
     *
     * @param task
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = true;
        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志数据
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(0);
            taskinfoLogsMapper.insert(taskinfoLogs);
        } catch (BeansException e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

}
